package com.chapter_1;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @Author: Timo
 * @Date: 2019/5/10 11:23
 * @Description: 测试多线程的返回值
 */
public class CallableTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        int taskSize = 5;
        // 创建一个线程池
        List<User> list = new ArrayList<User>();
        ExecutorService pool = Executors.newFixedThreadPool(taskSize);
        CompletionService<List<User>> s = new ExecutorCompletionService<List<User>>(pool);

        //创建多个有返回值的任务
        for(int i = 1 ; i <= taskSize ; i++){
            s.submit(new MyCallableThread(i));
        }


        for(int i = 1 ; i <= taskSize ; i++){
            try {
                Future<List<User>> f = s.take();
                f.get().forEach(ff ->{
                    ff.setUserName(ff.getUserName()+"_FF");
                });
                System.out.println(">>>>>"+f.get());
                list.addAll(f.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }


//        for (int i = 0; i < taskSize; i++) {
//            Callable<List<User>> c = new MyCallableThread(i);
//            Future<List<User>> f = pool.submit(c);
//            list.addAll(f.get());
//        }
        // 关闭线程池
        pool.shutdown();
        System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<");


        list.forEach(u -> {
            System.out.println("user:"+u);
        });
    }
}
